<template>
  <div class="contract-info-container">
    <el-button type="primary" @click="handleAddContract" style="margin-bottom: 10px">
      关联合同
    </el-button>

    <div v-if="loading" class="loading-state">
      <el-skeleton :rows="3" animated />
    </div>

    <div v-else-if="contractList.length === 0" class="empty-contract">
      <el-empty description="暂无关联合同" />
    </div>

    <div v-else class="contract-list">
      <div v-for="contract in contractList" :key="contract.id" class="contract-card">
        <div class="contract-header">
          <h4>{{ contract.cate_name }}</h4>
        </div>
        <div class="contract-details">
          <div class="detail-item">
            <span class="label">客户名称:</span>
            <span class="value">{{ contract.customer || contract.customer_name }}</span>
          </div>
          <div class="detail-item">
            <span class="label">签订日期:</span>
            <span class="value">{{ formatDate(contract.sign_time) }}</span>
          </div>
          <div class="detail-item">
            <span class="label">合同金额:</span>
            <span class="value amount">
              ¥{{ contract.cost ? parseFloat(String(contract.cost)).toFixed(2) : '0.00' }}
            </span>
          </div>
          <div class="detail-item">
            <span class="label">到账金额:</span>
            <span class="value amount">
              ¥{{ contract.cost2 ? parseFloat(String(contract.cost2)).toFixed(2) : '0.00' }}
            </span>
          </div>
          <div class="detail-item">
            <span class="label">后期费用:</span>
            <span class="value amount">{{ contract.cost3 }}</span>
          </div>
          <div class="detail-item">
            <span class="label">签订人:</span>
            <span class="value">{{ contract.sign_name }}</span>
          </div>
          <div class="detail-item">
            <span class="label">合同状态:</span>
            <span class="value status-badge" :class="getNewStatusClass(contract)">
              {{ getNewStatusText(contract) }}
            </span>
          </div>
          <div v-if="contract.remark" class="detail-item">
            <span class="label">备注:</span>
            <span class="value">{{ contract.remark }}</span>
          </div>
        </div>
        <div class="contract-actions">
          <el-button size="small" @click="handleViewContract(contract.id)">查看详情</el-button>
          <el-button size="small" type="danger" @click="handleRemoveContract(contract.id)">
            移除
          </el-button>
        </div>
      </div>
    </div>

    <!-- 合同选择器对话框 -->
    <el-dialog
      v-model="contractSelectorVisible"
      title="选择关联合同"
      width="800px"
      :before-close="handleContractSelectorClose"
    >
      <div class="contract-selector">
        <!-- 搜索栏 -->
        <div class="search-bar">
          <el-input
            v-model="searchForm.keywords"
            placeholder="请输入客户名称或合同编号"
            clearable
            style="width: 300px; margin-right: 10px"
            @keyup.enter="searchContracts"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
          <el-button type="primary" @click="searchContracts">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </div>

        <!-- 合同列表 -->
        <el-table
          :data="availableContracts"
          border
          style="width: 100%; margin-top: 20px"
          height="400"
          @row-click="handleRowClick"
        >
          <el-table-column width="55">
            <template #default="scope">
              <el-radio
                :model-value="selectedContractId"
                :label="scope.row.id"
                @click.stop="handleRadioChange(scope.row)"
              >
                &nbsp;
              </el-radio>
            </template>
          </el-table-column>
          <el-table-column prop="customer" label="客户名称" width="180" show-overflow-tooltip />
          <el-table-column prop="code" label="合同编号" width="180" show-overflow-tooltip />
          <el-table-column prop="sign_time" label="签约时间" width="120" />
          <el-table-column prop="cost" label="合同金额(元)" width="120" align="right" />
        </el-table>

        <!-- 分页 -->
        <div class="pagination-container">
          <el-pagination
            v-model:current-page="searchForm.page"
            v-model:page-size="searchForm.limit"
            :page-sizes="[10, 20, 50]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="contractTotal"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="contractSelectorVisible = false">取消</el-button>
          <el-button
            type="primary"
            @click="confirmContractSelection"
            :disabled="!selectedContractId"
          >
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
  import { ref, onMounted, watchEffect, watch } from 'vue'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import { Search } from '@element-plus/icons-vue'
  import request from '@/utils/request'
  import { contractApi } from '@/api/contract'

  // 定义合同接口
  interface Contract {
    id: number
    code: string
    name: string
    cate_name: string
    customer?: string
    customer_name?: string
    sign_date: string | number
    sign_time: string | number
    sign_name: string
    cost: number | string
    cost2: number | string
    cost3: string
    status: number
    stop_time?: number
    void_time?: number
    archive_time?: number
    remark?: string
    [key: string]: any
  }

  // 定义可关联的合同接口
  interface AvailableContract {
    id: number
    customer: string
    code: string
    sign_time: string
    cost: string
  }

  const props = defineProps<{
    caseId: number
    contractId?: number // 可选的合同ID参数
  }>()

  const emit = defineEmits<{
    (e: 'contract-linked'): void
  }>()

  const contractList = ref<Contract[]>([])
  const loading = ref(false)
  const lastContractId = ref<number | null>(null)

  // 合同选择器相关
  const contractSelectorVisible = ref(false)
  const availableContracts = ref<AvailableContract[]>([])
  const contractTotal = ref(0)
  const selectedContractId = ref<number | null>(null)
  const selectedContract = ref<AvailableContract | null>(null)
  const searchForm = ref({
    page: 1,
    limit: 10,
    keywords: '',
  })

  /**
   * 获取合同状态文本（新逻辑）
   * 优先检查时间字段，然后检查状态码
   */
  const getNewStatusText = (contract: Contract) => {
    // 检查时间字段
    if (contract.archive_time && contract.archive_time > 0) {
      return '已归档'
    }
    if (contract.void_time && contract.void_time > 0) {
      return '已作废'
    }
    if (contract.stop_time && contract.stop_time > 0) {
      return '已中止'
    }

    // 检查状态码
    const statusMap: Record<number, string> = {
      1: '草稿',
      2: '审核中',
      3: '已通过',
      4: '已拒绝',
      5: '已签订',
      6: '已完成',
      7: '已中止',
      8: '已作废',
    }

    return statusMap[contract.status] || '履约中'
  }

  /**
   * 获取合同状态样式类（新逻辑）
   * 优先检查时间字段，然后检查状态码
   */
  const getNewStatusClass = (contract: Contract) => {
    // 检查时间字段
    if (contract.archive_time && contract.archive_time > 0) {
      return 'status-archived'
    }
    if (contract.void_time && contract.void_time > 0) {
      return 'status-voided'
    }
    if (contract.stop_time && contract.stop_time > 0) {
      return 'status-suspended'
    }

    // 检查状态码
    const statusMap: Record<number, string> = {
      1: 'status-draft',
      2: 'status-reviewing',
      3: 'status-approved',
      4: 'status-rejected',
      5: 'status-signed',
      6: 'status-completed',
      7: 'status-suspended',
      8: 'status-voided',
    }

    return statusMap[contract.status] || 'status-default'
  }

  // 格式化日期
  const formatDate = (dateValue: string | number): string => {
    if (!dateValue) return ''

    try {
      // 处理时间戳
      const timeValue = typeof dateValue === 'string' ? parseInt(dateValue) : dateValue

      // 检查是否是秒级时间戳（10位左右），如果是则转换为毫秒级
      let timestamp = timeValue
      if (timeValue.toString().length <= 10) {
        timestamp = timeValue * 1000 // 秒级时间戳转换为毫秒级
      }

      const date = new Date(timestamp)

      // 检查是否是有效日期
      if (isNaN(date.getTime())) {
        // 尝试直接返回字符串形式的时间，可能已经是格式化好的
        return typeof dateValue === 'string' ? dateValue : ''
      }

      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')

      return `${year}-${month}-${day}`
    } catch (error) {
      console.error('日期格式化失败:', error)
      return typeof dateValue === 'string' ? dateValue : ''
    }
  }

  // 加载合同列表
  const loadContractList = async () => {
    // 合同信息加载开始

    // 如果合同编号为0，则不请求合同接口
    if (props.contractId === 0) {
      // 合同编号为0，跳过加载
      contractList.value = []
      return
    }

    // 防止重复请求
    if (lastContractId.value === props.contractId) {
      // 合同ID未变化，跳过重复请求
      return
    }

    loading.value = true
    try {
      // 优先使用contractId（如果提供），否则使用caseId作为备选方案
      const contractId = props.contractId || props.caseId

      if (!contractId) {
        console.error('ContractInfo: 没有有效的合同ID')
        ElMessage.warning('没有有效的合同ID，无法获取合同信息')
        contractList.value = []
        return
      }

      // 使用contractApi发送请求
      // 修复：使用contractApi.viewContract方法，确保参数格式正确
      try {
        // 增加参数验证，确保contractId有效
        if (!contractId || (typeof contractId !== 'string' && typeof contractId !== 'number')) {
          console.error('ContractInfo: 无效的合同ID:', contractId)
          ElMessage.error('无效的合同ID')
          contractList.value = []
          return
        }

        // 确保contractId是字符串类型，避免类型问题
        const response: any = await contractApi.viewContract({ id: String(contractId) })

        // 接口返回结果分析

        // 正确处理响应数据
        if (response && response.code !== undefined) {
          // 响应状态码处理
          // 响应状态码类型检查
          // 响应消息处理

          if (response.code === 0 && response.data) {
            contractList.value = [response.data]
          } else {
            ElMessage.error(response.msg || '获取合同信息失败')
            contractList.value = []
          }
        } else {
          ElMessage.error('获取合同信息失败：响应格式异常')
          contractList.value = []
        }
      } catch (error) {
        console.error('ContractInfo: 获取合同信息失败:', error)
        // 提供更详细的错误信息
        const errorObj = error as any
        if (errorObj.response) {
          ElMessage.error(
            `获取合同信息失败：${errorObj.response.status} ${errorObj.response.statusText || '服务器错误'}`
          )
        } else if (errorObj.code === 'ECONNABORTED') {
          ElMessage.error('获取合同信息超时，请稍后重试')
        } else if (errorObj.code === 'ECONNREFUSED') {
          ElMessage.error('无法连接到服务器，请检查网络连接')
        } else {
          ElMessage.error('获取合同信息失败，请稍后重试')
        }
        contractList.value = []
      }
    } catch (error) {
      console.error('ContractInfo: 获取合同信息失败:', error)
      ElMessage.error('获取合同信息失败，请稍后重试')
      contractList.value = []
    } finally {
      loading.value = false
      lastContractId.value = props.contractId ?? null
    }
  }

  // 添加合同 - 打开合同选择器
  const handleAddContract = () => {
    // 显示合同选择器对话框
    contractSelectorVisible.value = true

    // 重置搜索条件
    searchForm.value = {
      page: 1,
      limit: 10,
      keywords: '',
    }

    // 加载可用合同列表
    loadAvailableContracts()
  }

  // 加载可关联的合同列表
  const loadAvailableContracts = async () => {
    try {
      const response: any = await request({
        url: '/api/lawcase/cases/get_available_contracts',
        method: 'get',
        params: {
          page: searchForm.value.page,
          limit: searchForm.value.limit,
          keywords: searchForm.value.keywords,
        },
      })

      if (response.code === 0) {
        availableContracts.value = response.data.data || []
        contractTotal.value = response.data.total || 0
      } else {
        ElMessage.error(response.msg || '获取合同列表失败')
      }
    } catch (error) {
      console.error('获取合同列表失败:', error)
      ElMessage.error('获取合同列表失败')
    }
  }

  // 搜索合同
  const searchContracts = () => {
    searchForm.value.page = 1
    loadAvailableContracts()
  }

  // 重置搜索
  const resetSearch = () => {
    searchForm.value.keywords = ''
    searchForm.value.page = 1
    loadAvailableContracts()
  }

  // 处理分页大小改变
  const handleSizeChange = (val: number) => {
    searchForm.value.limit = val
    searchForm.value.page = 1
    loadAvailableContracts()
  }

  // 处理当前页改变
  const handleCurrentChange = (val: number) => {
    searchForm.value.page = val
    loadAvailableContracts()
  }

  // 处理单选框变化
  const handleRadioChange = (contract: AvailableContract) => {
    selectedContractId.value = contract.id
    selectedContract.value = contract
  }

  // 处理行点击事件
  const handleRowClick = (row: AvailableContract) => {
    handleRadioChange(row)
  }

  // 确认合同选择
  const confirmContractSelection = async () => {
    if (!selectedContract.value) {
      ElMessage.warning('请选择要关联的合同')
      return
    }

    try {
      const response: any = await request({
        url: '/api/lawcase/cases/link_contract',
        method: 'post',
        data: {
          case_id: props.caseId,
          contract_id: selectedContract.value.id,
        },
      })

      if (response.code === 0) {
        ElMessage.success('关联合同成功')
        contractSelectorVisible.value = false
        // 重置选择
        selectedContractId.value = null
        selectedContract.value = null
        emit('contract-linked')
        loadContractList()
      } else {
        ElMessage.error(response.msg || '关联合同失败')
      }
    } catch (error) {
      console.error('关联合同失败:', error)
      ElMessage.error('关联合同失败')
    }
  }

  // 关闭合同选择器前的处理
  const handleContractSelectorClose = (done: () => void) => {
    ElMessageBox.confirm('确定要关闭合同选择器吗？')
      .then(() => {
        done()
      })
      .catch(() => {
        // 用户取消关闭
      })
  }

  // 查看合同详情
  const handleViewContract = (contractId: number) => {
    ElMessage.info('查看合同详情功能开发中...')
  }

  // 移除合同 - 解除关联
  const handleRemoveContract = async (contractId: number) => {
    try {
      await ElMessageBox.confirm('确定要解除与该合同的关联吗？', '确认解除', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })

      const response: any = await request({
        url: '/api/lawcase/cases/unlink_contract',
        method: 'post',
        data: {
          case_id: props.caseId,
        },
      })

      if (response.code === 0) {
        ElMessage.success('解除关联合同成功')
        emit('contract-linked')
        loadContractList()
      } else {
        ElMessage.error(response.msg || '解除关联合同失败')
      }
    } catch (error) {
      // 用户取消操作或请求失败
      if (error !== 'cancel') {
        console.error('解除关联合同失败:', error)
        ElMessage.error('解除关联合同失败')
      }
    }
  }

  // 组件挂载时加载合同列表
  onMounted(() => {
    loadContractList()
  })

  // 监听props变化，当contractId改变时重新加载合同数据
  watch(
    () => props.contractId,
    (newVal, oldVal) => {
      // 只有当contractId发生变化时才重新加载
      if (newVal !== oldVal && newVal !== undefined) {
        loadContractList()
      }
    },
    { immediate: false }
  )
</script>

<style scoped>
  .contract-info-container {
    padding: 5px 0;
    min-width: 250px; /* 设置最小宽度 */
  }

  .loading-state {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 40px 0;
    color: #909399;
  }

  .empty-contract {
    padding: 40px 0;
    text-align: center;
  }

  .contract-list {
    display: flex;
    flex-direction: column;
    gap: 15px;
  }

  .contract-card {
    border: 1px solid #e6e6e6;
    border-radius: 8px;
    padding: 16px;
    background-color: #fafafa;
  }

  .contract-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 12px;
    padding-bottom: 8px;
    border-bottom: 1px solid #eee;
  }

  .contract-header h4 {
    margin: 0;
    font-size: 14px;
    color: #333;
    font-weight: 500;
  }

  .contract-number {
    font-size: 12px;
    color: #909399;
  }

  .contract-details {
    display: flex;
    flex-direction: column;
    gap: 8px;
    margin-bottom: 12px;
  }

  .detail-item {
    display: flex;
    justify-content: space-between;
    font-size: 13px;
  }

  .detail-item .label {
    color: #606266;
  }

  .detail-item .value {
    color: #303133;
    font-weight: 500;
  }

  .detail-item .amount {
    color: #f56c6c;
  }

  .contract-actions {
    display: flex;
    justify-content: flex-end;
    gap: 10px;
    padding-top: 8px;
    border-top: 1px solid #eee;
  }

  /* 合同状态样式 */
  .status-badge {
    padding: 2px 6px;
    border-radius: 4px;
    font-size: 12px;
    font-weight: 500;
  }

  .status-draft {
    background-color: #e3f2fd;
    color: #1976d2;
  }

  .status-reviewing {
    background-color: #fff3e0;
    color: #f57c00;
  }

  .status-approved {
    background-color: #f1f8e9;
    color: #558b2f;
  }

  .status-rejected {
    background-color: #fce4ec;
    color: #c2185b;
  }

  .status-signed {
    background-color: #e8f5e9;
    color: #2e7d32;
  }

  .status-completed {
    background-color: #e0f2f1;
    color: #00695c;
  }

  .status-suspended {
    background-color: #f3e5f5;
    color: #7b1fa2;
  }

  .status-voided {
    background-color: #fafafa;
    color: #757575;
  }

  .status-archived {
    background-color: #e1f5fe;
    color: #01579b;
  }

  .status-default {
    background-color: #eeeeee;
    color: #757575;
  }

  /* 合同选择器样式 */
  .search-bar {
    display: flex;
    align-items: center;
    margin-bottom: 20px;
  }

  .pagination-container {
    display: flex;
    justify-content: flex-end;
    margin-top: 20px;
  }

  .dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 10px;
  }
</style>
